<script lang="ts" setup>
import type { SysReceiptRecordDetails } from '@/api/types/finance'
import { computed, ref } from 'vue'
import { getReceiptRecordReleaseById, getSysReceiptRecordDetails } from '@/api/finance'
import ApprovalActionBar from '@/components/ApprovalActionBar.vue'
import { useFlow } from '@/hooks/useFlow'

definePage({
  style: {
    navigationBarTitleText: '释放保证金详情',
  },
})

// 使用流程hook
const {
  currentProcess,
  getProcessInstance,
  getCurrentUserPendingTaskId,
  loading: flowLoading,
} = useFlow()

// 流程ID
const flowIdValue = ref<string>('')
const idValue = ref<string>('')

// 业务ID
const businessId = computed(() => {
  if (currentProcess.value?.businessKey) {
    return currentProcess.value.businessKey
  }
  if (currentProcess.value?.formVariables?.BUSINESS_KEY) {
    return currentProcess.value.formVariables.BUSINESS_KEY
  }
  return ''
})

// 业务详情数据
const businessDetail = ref<SysReceiptRecordDetails | null>(null)
const businessLoading = ref(false)
const businessError = ref('')

// 获取流程实例信息
async function fetchProcessInfo(id: string) {
  try {
    await getProcessInstance(id)
    // 获取当前用户待审批任务ID
    const taskId = await getCurrentUserPendingTaskId(idValue.value)
    if (taskId) {
      flowIdValue.value = taskId
    }
    // 从流程实例中提取节点信息
    if (currentProcess.value?.processDefinition) {
      console.log('流程定义信息:', currentProcess.value.processDefinition)
    }

    // 流程信息获取成功后，自动获取业务详情
    if (businessId.value) {
      await fetchReleaseOfSecurityDepositDetail()
    }
  }
  catch (error) {
    console.error('获取流程信息失败:', error)
    uni.showToast({
      title: '获取流程信息失败',
      icon: 'none',
    })
  }
}

// 获取保证金详情
async function fetchReleaseOfSecurityDepositDetail() {
  if (!businessId.value)
    return

  businessLoading.value = true
  businessError.value = ''

  try {
    // 先获取流程实例信息
    const release = await getReceiptRecordReleaseById(businessId.value)
    // 从流程实例中提取节点信息
    if (release?.receiptId) {
      const res = await getSysReceiptRecordDetails(release?.receiptId)
      businessDetail.value = res.data || null
    }
  }
  catch (error) {
    console.error('获取保证金详情失败:', error)
    businessError.value = '获取保证金详情失败'
    uni.showToast({
      title: '获取保证金详情失败',
      icon: 'none',
    })
  }
  finally {
    businessLoading.value = false
  }
}

// 页面加载时获取数据
onLoad((e) => {
  console.log('页面参数:', e)
  flowIdValue.value = e?.flowId || ''
  idValue.value = e?.id || ''
  if (!e.id) {
    uni.showToast({
      title: '没有获取到id',
      icon: 'none',
    })
    return
  }
  fetchProcessInfo(e.id)
})

// // 页面显示时也刷新数据
// onShow(() => {
//   fetchProcessInfo()
// })
</script>

<template>
  <view class="page p-4">
    <!-- 审批状态卡片 -->
    <ApprovalStatusCard :current-process="currentProcess" :id-value="idValue" />

    <!-- 加载状态 -->
    <view v-if="flowLoading || businessLoading" class="flex flex-col items-center justify-center py-10">
      <view class="text-gray-500">
        加载中...
      </view>
    </view>

    <!-- 业务详情展示 -->
    <view v-else-if="businessDetail" class="space-y-4">
      <!-- 基本信息卡片 -->
      <view class="border border-gray-100 rounded-lg bg-white p-4 shadow-md">
        <view class="mb-3 border-b border-gray-100 pb-2 text-lg text-gray-800 font-medium">
          保证金基本信息
        </view>
        <view class="flex flex-col gap-y-3 text-sm">
          <view class="flex justify-between">
            <span class="text-gray-500">业务编号:</span>
            <span class="text-gray-800">{{ businessDetail.businessNo || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">金额:</span>
            <span class="text-gray-800 font-medium">{{ businessDetail.amount || 0 }} 元</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">业务机构:</span>
            <span class="text-gray-800">{{ businessDetail.businessInstitutionName || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">业务部门:</span>
            <span class="text-gray-800">{{ businessDetail.businessDepartmentName || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">业务员:</span>
            <span class="text-gray-800">{{ businessDetail.salesmanName || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">状态:</span>
            <span class="text-gray-800">
              {{ businessDetail.status === 1 ? '正常' : businessDetail.status === 2 ? '已释放' : businessDetail.status === 3 ? '已冻结' : '-' }}
            </span>
          </view>
        </view>
      </view>

      <!-- 收款信息卡片 -->
      <view class="border border-gray-100 rounded-lg bg-white p-4 shadow-md">
        <view class="mb-3 border-b border-gray-100 pb-2 text-lg text-gray-800 font-medium">
          收款信息
        </view>
        <view class="flex flex-col gap-y-3 text-sm">
          <view class="flex justify-between">
            <span class="text-gray-500">收款实体:</span>
            <span class="text-gray-800">{{ businessDetail.receivingEntity || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">收款银行:</span>
            <span class="text-gray-800">{{ businessDetail.receivingBank || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">收款账户:</span>
            <span class="text-gray-800">{{ businessDetail.receivingAccount || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">收款事项:</span>
            <span class="text-gray-800">{{ businessDetail.receiptEvent || '-' }}</span>
          </view>
        </view>
      </view>

      <!-- 付款信息卡片 -->
      <view class="border border-gray-100 rounded-lg bg-white p-4 shadow-md">
        <view class="mb-3 border-b border-gray-100 pb-2 text-lg text-gray-800 font-medium">
          付款信息
        </view>
        <view class="flex flex-col gap-y-3 text-sm">
          <view class="flex justify-between">
            <span class="text-gray-500">付款实体:</span>
            <span class="text-gray-800">{{ businessDetail.payerEntity || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">付款银行:</span>
            <span class="text-gray-800">{{ businessDetail.payerBank || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">付款账户:</span>
            <span class="text-gray-800">{{ businessDetail.payerAccount || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">付款时间:</span>
            <span class="text-gray-800">{{ businessDetail.payTime || '-' }}</span>
          </view>
        </view>
      </view>

      <!-- 其他信息卡片 -->
      <view class="border border-gray-100 rounded-lg bg-white p-4 shadow-md">
        <view class="mb-3 border-b border-gray-100 pb-2 text-lg text-gray-800 font-medium">
          其他信息
        </view>
        <view class="text-sm space-y-3">
          <view class="flex justify-between">
            <span class="text-gray-500">创建时间:</span>
            <span class="text-gray-800">{{ businessDetail.createTime || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">创建人:</span>
            <span class="text-gray-800">{{ businessDetail.createName || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">备注:</span>
            <span class="text-gray-800">{{ businessDetail.remark || '-' }}</span>
          </view>
        </view>
      </view>

      <!-- 流程信息卡片（可选显示） -->
      <view class="border border-gray-100 rounded-lg bg-white p-4 shadow-md">
        <view class="mb-3 border-b border-gray-100 pb-2 text-lg text-gray-800 font-medium">
          流程信息
        </view>
        <view v-if="currentProcess" class="flex flex-col gap-y-3 text-sm">
          <view class="flex justify-between">
            <span class="text-gray-500">流程名称:</span>
            <span class="text-gray-800">{{ currentProcess.name || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">流程状态:</span>
            <span class="text-gray-800">{{ currentProcess.status === 1 ? '进行中' : '已结束' }}</span>
          </view>
        </view>
        <view v-else class="py-2 text-center text-gray-500">
          暂无流程信息
        </view>
      </view>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="businessError" class="py-10 text-center text-gray-500">
      {{ businessError }}
      <button class="mt-3 text-blue-500" @click="fetchProcessInfo">
        重新获取
      </button>
    </view>

    <!-- 无数据状态 -->
    <view v-else class="py-10 text-center text-gray-500">
      暂无业务信息
    </view>

    <!-- 审批操作栏组件 -->
    <ApprovalActionBar
      v-if="flowIdValue && currentProcess?.status === 1"
      :process-id="flowIdValue"
    />
  </view>
</template>

<style lang="scss" scoped>
// 页面样式
.page {
  padding-bottom: 80px; // 为底部操作栏留出空间
}
</style>
